home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Tech Arsenal 1
/
Tech Arsenal (Arsenal Computer).ISO
/
tek-01
/
msoftapp.zip
/
SORT2.CPP
< prev
next >
Wrap
C/C++ Source or Header
|
1993-06-01
|
2KB
|
95 lines
////////////////////////////////////////////////////////////////
// Sort program re-written with generic "comparable" objects
//
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream.h>
//////////////////
// Abstract "comparable" object
//
class CmpObj {
static int QSortFn(const void* v1, const void* v2);
public:
static void Sort(CmpObj** array, int len);
// pure virtual function: each derived class
// must provide its own implementation.
virtual int compare(CmpObj* c2) = 0;
};
//////////////////
// Private static function passed to qsort works for
// all class derived from CmpObj, since "compare" is virtual
//
int CmpObj::QSortFn(const void* v1, const void* v2)
{
CmpObj* c1 = *(CmpObj**)v1;
CmpObj* c2 = *(CmpObj**)v2;
// call class-specific virtual compare function
return c1->compare(c2);
}
//////////////////
// Sort an array of pointers to CmpObj objects.
// This is what callers use to sort an array.
//
void CmpObj::Sort(CmpObj** array, int len)
{
qsort(array, len, sizeof(CmpObj*), QSortFn);
}
//////////////////
// Now Person is derived from CmpObj, because
// Persons are comparable objects.
//
class Person : public CmpObj {
char name[20];
public:
Person(const char* n) { strcpy(name, n); }
void print() { cout << name << '\n'; };
int compare(CmpObj* c2);
};
//////////////////
// Compare function for Person just compares name strings.
//
int Person::compare(CmpObj* p2)
{
return strcmp(name, ((Person*)p2)->name);
}
// Some sample people (unsorted).
Person people[] = {
{ "Cynthia" },
{ "Sandy" },
{ "Carl" },
{ "Alfred" },
{ "Beth" },
};
const NPEOPLE = sizeof(people)/sizeof(Person);
/////////////////
// Main program loop:
// create array of pointers, sort it, then print.
//
int main(int, char**)
{
Person *array[NPEOPLE];
// Initialize array of pointers from sample Persons
for (int i=0; i<NPEOPLE; i++)
array[i] = &people[i];
// sort the array
CmpObj::Sort((CmpObj**)array, NPEOPLE);
// print
for (i=0; i<NPEOPLE; i++)
array[i]->print();
return 0;
}